import {Toast} from 'antd-mobile'
import {storage} from './index'
import axios from 'axios'

export default function Http({
                               url,
                               method = 'post',
                               headers = {},
                               body = {},
                               params = {},
                               setLoading,
                               setResult
                             }) {
  setLoading && setLoading(true)

  const token = storage.get('token')

  let defaultHeader = {
    'Content-type': 'application/json'
  }

  defaultHeader = token ? {
    ...defaultHeader,
    token
  } : defaultHeader

  let temp
  if (method.toUpperCase() === 'GET') {
    temp = {
      headers: {
        ...defaultHeader,
        ...headers
      },
      method,
      params
    }
  } else {
    temp = {
      headers: {
        ...defaultHeader,
        ...headers
      },
      method,
      data: JSON.stringify(body)
    }
  }

  return new Promise((resolve, reject) => {
    axios({
      url: '/api' + url,
      ...temp
    }).then(res => res.data)
      .then(res => {
        const {success, data, status, message} = res
        if (success) {
          resolve(data)
          setResult && setResult(data)
        } else {
          if (status === 403) {
            storage.clear()
            setTimeout(() => {
              window.location.href = '/login'
            }, 200)
          }
          Toast.fail(message)
          reject(message)
        }
      })
      .catch(err => {
        Toast.fail(err)
        reject(err)
      })
      .finally(() => {
        setLoading && setLoading(false)
      })
  })
}
